package com.veltri.JDroid;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TabOneActivity extends Activity {
	// self is used to refer to this activity when need be referenced in a
	// method
	TabOneActivity self = null;

	// declare layout elements
	private ListView tabOneListView;

	// declare sessionId
	String sessionId;
	ArrayList<String> articleTitles = new ArrayList<String>();
	private Hashtable<String, String> idTable;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		self = this;

		// set view to list of first tab
		setContentView(R.layout.tab_one_layout);

		// instantiate layout elements
		tabOneListView = (ListView) findViewById(R.id.tab_one_list);

		// Instantiate variables
		idTable = new Hashtable<String, String>();
		sessionId = ((MyApplication) this.getApplication()).getSessionId();
		new UpdateTabOne().execute();
	}

	// execute HttpRequest in its own thread
	private class UpdateTabOne extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {

			// set up HTTP Post
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://m.jdroid.co/article_list.php");

			// get device ID
			final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
			String deviceID = tm.getDeviceId();
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			try {

				// create name-value pairs to be sent with HTTP Request
				nameValuePairs.add(new BasicNameValuePair("device_id", deviceID));
				nameValuePairs.add(new BasicNameValuePair("session_id", sessionId));
				((MyApplication) self.getApplication()).setCategories();
				int myCategory = ((MyApplication) self.getApplication()).getCategory(0);
				nameValuePairs.add(new BasicNameValuePair("category_id", Integer.toString(myCategory)));				
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// add header that ensures HTTP Request is being made from Android device
				httppost.addHeader("User-Agent", LoginActivity.UserAgent);

				// execute HTTP Request
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity resEntityGet = response.getEntity();

				// get raw JSON response
				String rawResponse = "";
				if (resEntityGet != null) {
					rawResponse = EntityUtils.toString(resEntityGet);
				}

				// decode JSON response
				// gets ArrayList of articles titles
				// gets hash table of article title and id (key and value)
				JSONObject wholeResponse = new JSONObject(rawResponse);
				int timestamp = wholeResponse.getInt("current_time");
				((MyApplication) self.getApplication()).setTimestamp( 0, timestamp);
				
				JSONArray rootArray = wholeResponse.getJSONArray("article_list");
				int len = rootArray.length();
				for (int i = 0; i < len; ++i) {
					JSONObject obj = rootArray.getJSONObject(i);
					String article_id = obj.getString("id");
					String article_title = obj.getString("title");
					articleTitles.add(article_title);
					idTable.put(article_title, article_id);
				}
				return "";

			} catch (Exception e) {
				Log.e("JSON Parse", "response parsing failed - tab one article list");
			}
			return null;
		}

		@Override
		public void onPostExecute(String result) {

			// fill list view with article titles
			tabOneListView.setAdapter(new ArrayAdapter<String>(self, android.R.layout.simple_list_item_1, articleTitles));
			tabOneListView.setTextFilterEnabled(true);

			// create click listener for each article
			// opens article in a webview
			tabOneListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

					// set up HTTP POST Request
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost( "http://m.jdroid.co/article.php");

					// get device id
					final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
					String deviceID = tm.getDeviceId();
					try {
						// create name-value pairs to be sent with HTTP Request
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
						
						nameValuePairs.add(new BasicNameValuePair("device_id",deviceID));
						nameValuePairs.add(new BasicNameValuePair("session_id", sessionId));
						
						String currentArticleTitle = ((TextView) view).getText().toString();
						String currentArticleId = idTable.get(currentArticleTitle).toString();						
						nameValuePairs.add(new BasicNameValuePair("article_id", currentArticleId));
						
						((MyApplication) self.getApplication()).setCategories();
						int myCategory = ((MyApplication) self.getApplication()).getCategory(0);
						nameValuePairs.add(new BasicNameValuePair("category_id", Integer.toString(myCategory)));
						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

						// add header that ensures HTTP Request is being made from Android device
						httppost.addHeader("User-Agent", LoginActivity.UserAgent);

						// get raw JSON response
						HttpResponse response = httpclient.execute(httppost);
						
						int responseCode = response.getStatusLine().getStatusCode();
						
						if( responseCode == HttpStatus.SC_OK) {
							HttpEntity resEntityGet = response.getEntity();
							String rawResponse = "";
							if (resEntityGet != null) {
								rawResponse = EntityUtils.toString(resEntityGet);
							}

							// decode JSON response
							JSONObject jObject = new JSONObject(rawResponse);
							String intro = jObject.getString("introtext");
							String fullarticle = jObject.getString("fulltext");
							String html = intro + fullarticle;

							// open article in webview using JSON decoded HTML
							Intent intent = new Intent(getBaseContext(), WebViewActivity.class);
							intent.putExtra("HTML_RESPONSE", html);
							intent.putExtra("ARTICLE_TITLE", ((TextView) view).getText().toString());
							startActivity(intent);
						} else {
							if (responseCode == HttpStatus.SC_FORBIDDEN) {
								Log.e("TABONE", "Received 404 From Server"); 
								Toast.makeText(TabOneActivity.this,
										"Error: Not Logged In", Toast.LENGTH_SHORT)
										.show();
								// Logout
								((MyApplication) self.getApplication()).setSessionId("");
								Intent myIntent = new Intent(self, LoginActivity.class);
								startActivityForResult(myIntent, 0);
							} else {
								Log.e("TABONE", "Received non 404/200 From Server - " + Integer.toString( responseCode));
							}
							
						}					

					} catch (Exception e) {
						Log.e("JSON Parse", "response parsing failed in tab one - article");
						e.printStackTrace();
					}
				}
			});

		}
	}

	// disable back button (logout button under options menu should be used for
	// proper logout)
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onResume() {
		super.onResume();
		boolean update = ((MyApplication) self.getApplication()).isReloadTab();
		if( update) {
			new UpdateTabOne().execute();
			((MyApplication) self.getApplication()).setReloadTab(false);
		}
	}
}
